package com.ciwong.epaper.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.aliyun.sls.android.sdk.ClientConfiguration;
import com.aliyun.sls.android.sdk.LOGClient;
import com.aliyun.sls.android.sdk.LogException;
import com.aliyun.sls.android.sdk.SLSLog;
import com.aliyun.sls.android.sdk.core.auth.PlainTextAKSKCredentialProvider;
import com.aliyun.sls.android.sdk.core.callback.CompletedCallback;
import com.aliyun.sls.android.sdk.model.LogGroup;
import com.aliyun.sls.android.sdk.request.PostLogRequest;
import com.aliyun.sls.android.sdk.result.PostLogResult;
import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.LoginErrorLog;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.utils.StatUtils;
import com.ciwong.mobilelib.utils.ThreadTask;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by neo  on 2016/10/24.
 */
public class FeedbackUtil {

    public static String endpoint = "cn-beijing.log.aliyuncs.com";
    public static String accesskeyID = "LTAIU7XHJMbRcPGl";
    public static String accessKeySecret = "VIeyMSt4Vr1wXvGpjAdxoVMK48j3Ti";
    public static String project = "epaper";
    public static String logStore = "app";
    public static String loginStore = "userlogin";

    //听说模考反馈
    public static final int FEEDBACK_TYPE_LISTEN_SPEAK_WORK = 0;
    //句子跟读
    public static final int FEEDBACK_TYPE_SENTENCE_SPEECH = 1;
    //单词跟读
    public static final int FEEDBACK_TYPE_WORD_SPEECH = 2;

    //线上作答 反馈
    public static final int FEEDBACK_TYPE_ONLINE_ANSWER = 3;

    //互动教程 反馈
    public static final int FEEDBACK_TYPE_INTERACTIVE_TUTORIAL = 4;
    //作业列表
    public static final int FEEDBACK_TYPE_HOMEWORK_LIST = 5;
    //已完成作业列表
    public static final int FEEDBACK_TYPE_HASDONE__HOMEWORK_LIST = 6;


    //练习册
    public static final int FEEDBACK_TYPE_WORD_LIST = 7;
    //书桌
    public static final int FEEDBACK_TYPE_BOOK_DESK = 8;
    public static final int FEEDBACK_TYPE_SCAN_MODE = 9;
    public static final int FEEDBACK_TYPE_SYMBOL = 10;

    public static final int FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST = 11;
    public static final int FEEDBACK_TYPE_DICTATION = 12;
    public static final int FEEDBACK_TYPE_MESSAGE = 13;

    //提交作业反馈
    public static final int FEEDBACK_TYPE_SUBMIT_WORK = 101;
    //阿里云提交作业结果，成功或者失败
    public static final int FEEDBACK_TYPE_ALIYUN_SUBMIT_WORK_RESULT = 102;

    //下载资源
    public static final int FEEDBACK_TYPE_DOWNLOAD_RES = 103;
    //云之声评分
    public static final int FEEDBACK_TYPE_EVALUATE = 104;


    //内存泄漏日志
    public static final int FEEDBACK_MEMORY_LEAK = 1001;

    //请求错误
    public static final int FEEDBACK_TYPE_REQUEST_ERROR = 110;


    //崩溃日志
    public static final int FEEDBACK_CRASH_TRACE_INFO = 113;

    //在自定义服务中上传音频
    public static final int FEEDBACK_TYPE_SERVICE_UPLOAD_AUDIO = 20;

    //录音失败
    public static final int FEEDBACK_TYPE_MP3RECORDER = 105;

    private final static String TAG = "FeedbackUtil";

    private static FeedbackUtil instance;

    private static Context mContext;

    private static String app_IP;

    private FeedbackUtil() {
    }


    public static FeedbackUtil getInstance() {
        if (null == instance) {
            syn();
        }
        return instance;
    }

    private static synchronized void syn() {
        if (null == instance) {
            instance = new FeedbackUtil();
        }
    }

    /**
     * 设置上下文对象
     *
     * @param context 上下文对象
     */
    public static void setContext(Context context) {
        mContext = context;
    }


    public void getLog(int errorType, String logDesc, String remark) {
        //提交错误 类型
        //        addFeedbackLog(errorType, logDesc, remark, new BaseCallBack() {
        //            @Override
        //            public void failed(int errorCode, Object data) {
        //            }
        //
        //            @Override
        //            public void failed(Object data) {
        //            }
        //
        //            @Override
        //            public void success() {
        //                super.success();
        //            }
        //        });
    }


    public void addFeedbackLog(final int errorType, final String logDesc, final String remark, boolean openByServer) {
        asyncUploadLog(errorType, logDesc, remark);
    }


    public void addFeedbackLog(final int errorType, final String logDesc, final String remark) {
        asyncUploadLog(errorType, logDesc, remark);
    }

    public void addFeedbackLogWithJson(final int errorType, final String logDesc, final String json, final String remark) {
        String dealLogDesc = logDesc + " 答案json为:" + json;
        asyncUploadLog(errorType, dealLogDesc, remark);
    }

    public void addFeedLockLog(LoginErrorLog errorLog) {
        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.LOGIN_ERROR_TAG,
                errorLog, false);
    }


    /*
     *  推荐使用的方式，直接调用异步接口，通过callback 获取回调信息
     */
    private void asyncUploadLog(final int errorType, final String logDesc, final String remark) {
        ThreadTask.getInstance().executorNetThread(new Runnable() {
            @Override
            public void run() {
                String appVersion = getAppVersionName(mContext);
                String appName = getAppName(mContext);
                //        手机型号
                String netType = getIPProvider(mContext) + " " + GetNetworkType(mContext);
                PlainTextAKSKCredentialProvider credentialProvider = new PlainTextAKSKCredentialProvider(accesskeyID, accessKeySecret);
                ClientConfiguration conf = new ClientConfiguration();
                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
                SLSLog.enableLog(); // log打印在控制台
                LOGClient logClient = new LOGClient(endpoint, credentialProvider, conf);
                /* 创建logGroup */
                LogGroup logGroup = new LogGroup("android", netType);
                /* 存入一条log */
                com.aliyun.sls.android.sdk.model.Log log = new com.aliyun.sls.android.sdk.model.Log();

                log.PutContent("current_time", CWUtils.formatDate1(System.currentTimeMillis()));
                log.PutContent("brandId", String.valueOf(EApplication.BRAND_ID));
                log.PutContent("clientId", EConstants.CLIENT_ID);
                log.PutContent("agentType", "Android");
                log.PutContent("appName", appName);
                log.PutContent("appVersion", appVersion);
                log.PutContent("phoneVersion", android.os.Build.MODEL);
                log.PutContent("osVersion", "Android" + android.os.Build.VERSION.RELEASE);
                log.PutContent("environmentName", getEnvironmentName());
                log.PutContent("netWorkType", netType);
                log.PutContent("errorType", getModuleNameByFeedBackId(errorType));
                log.PutContent("logDesc", logDesc);
                log.PutContent("remark", remark);
                log.PutContent("userId", StatUtils.userId + "");
                UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
                if (userInfoBase != null) {
                    log.PutContent("userId", userInfoBase.getUserId() + "");
                    log.PutContent("userName", userInfoBase.getRealName());
                }
                logGroup.PutLog(log);

                try {
                    PostLogRequest request = new PostLogRequest(project, logStore, logGroup);
                    logClient.asyncPostLog(request, new CompletedCallback<PostLogRequest, PostLogResult>() {
                        @Override
                        public void onSuccess(PostLogRequest request, PostLogResult result) {
                            Log.d(TAG, "####asyncPostLog onSuccess#########");
                        }

                        @Override
                        public void onFailure(PostLogRequest request, LogException exception) {

                            Log.d(TAG, "####asyncPostLog exception#########" + exception.getMessage());

                        }
                    });

                } catch (LogException e) {

                    Log.d(TAG, "####asyncPostLog LogException#########" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    /*
     *  上报登录信息（登录、刷新token之后调用）
     *  推荐使用的方式，直接调用异步接口，通过callback 获取回调信息
     */
    public void asyncUploadUserLogin() {
        ThreadTask.getInstance().executorNetThread(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "####asyncUploadUserLogin start#########");
                String appVersion = getAppVersionName(mContext);
                String appName = getAppName(mContext);
                //手机型号
                String netType = getIPProvider(mContext) + " " + GetNetworkType(mContext);
                PlainTextAKSKCredentialProvider credentialProvider = new PlainTextAKSKCredentialProvider(accesskeyID, accessKeySecret);
                ClientConfiguration conf = new ClientConfiguration();
                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
                SLSLog.enableLog(); // log打印在控制台
                LOGClient logClient = new LOGClient(endpoint, credentialProvider, conf);
                /* 创建logGroup */
                LogGroup logGroup = new LogGroup("android", netType);
                /* 存入一条log */
                com.aliyun.sls.android.sdk.model.Log log = new com.aliyun.sls.android.sdk.model.Log();

                log.PutContent("current_time", CWUtils.formatDate1(System.currentTimeMillis()));
                log.PutContent("brandId", String.valueOf(EApplication.BRAND_ID));
                log.PutContent("clientId", EConstants.CLIENT_ID);
                log.PutContent("agentType", "Android");
                log.PutContent("appName", appName);
                log.PutContent("appVersion", appVersion);
                log.PutContent("phoneVersion", android.os.Build.MODEL);
                log.PutContent("osVersion", "Android" + android.os.Build.VERSION.RELEASE);
                log.PutContent("environmentName", getEnvironmentName());
                log.PutContent("netWorkType", netType);
                log.PutContent("userId", StatUtils.userId + "");
                UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
                if (userInfoBase != null) {
                    log.PutContent("userId", userInfoBase.getUserId() + "");
                    log.PutContent("userName", userInfoBase.getRealName());
                }
                logGroup.PutLog(log);

                try {
                    PostLogRequest request = new PostLogRequest(project, loginStore, logGroup);
                    logClient.asyncPostLog(request, new CompletedCallback<PostLogRequest, PostLogResult>() {
                        @Override
                        public void onSuccess(PostLogRequest request, PostLogResult result) {
                            Log.d(TAG, "####asyncUploadUserLogin onSuccess#########");
                        }

                        @Override
                        public void onFailure(PostLogRequest request, LogException exception) {

                            Log.d(TAG, "####asyncUploadUserLogin exception#########" + exception.getMessage());

                        }
                    });

                } catch (LogException e) {
                    Log.d(TAG, "####asyncUploadUserLogin LogException#########" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    public void addFeedbackLog(final int errorType, final String logDesc, final String remark, final BaseCallBack callBack) {
        //        if (!BaseRequest.isLogOpen()) {
        //            return;
        //        }
        ThreadTask.getInstance().executorNetThread(new Runnable() {
            @Override
            public void run() {
                String appVersion = getAppVersionName(mContext);
                //        手机型号
                String netType = getIPProvider(mContext) + " " + GetNetworkType(mContext);

                MeDao.getInstance().addFeedbackLog(EApplication.BRAND_ID, appVersion, android.os.Build.MODEL, "Android" + android.os.Build.VERSION.RELEASE, netType, errorType, logDesc, remark, callBack);
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);

    }

    //获取当前版本号
    private String getAppVersionName(Context context) {
        String versionName = "未知版本";
        try {
            versionName = context.getString(R.string.version, context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

    public String GetNetworkType(Context context) {
        try {
            String strNetworkType = "";
            NetworkInfo networkInfo;
            networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

            if (networkInfo != null && networkInfo.isConnected()) {
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    strNetworkType = "WIFI";
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    String _strSubTypeName = networkInfo.getSubtypeName();
                    Log.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);
                    // TD-SCDMA   networkType is 17
                    int networkType = networkInfo.getSubtype();
                    switch (networkType) {
                        case TelephonyManager.NETWORK_TYPE_GPRS:
                        case TelephonyManager.NETWORK_TYPE_EDGE:
                        case TelephonyManager.NETWORK_TYPE_CDMA:
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
                        case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
                            strNetworkType = "2G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_UMTS:
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
                        case TelephonyManager.NETWORK_TYPE_EVDO_A:
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
                        case TelephonyManager.NETWORK_TYPE_HSPA:
                        case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
                        case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
                        case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
                            strNetworkType = "3G";
                            break;
                        case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
                            strNetworkType = "4G";
                            break;
                        default:
                            // http:item/TD-SCDMA 中国移动 联通 电信 三种3G制式
                            if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
                                strNetworkType = "3G";
                            } else {
                                strNetworkType = _strSubTypeName;
                            }
                            break;
                    }
                    Log.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
                }
            }
            Log.e("cocos2d-x", "Network Type : " + strNetworkType);
            return strNetworkType;
        } catch (Exception e) {
            e.getStackTrace();
        }
        return null;
    }


    /**
     * 获取本机外网IP地址
     *
     * @param context
     * @return IP地址
     */
    public static String getIPProvider(Context context) {
        if (app_IP != null) {
            CWLog.i("byou", "app_IP==" + app_IP);
            return app_IP;
        }
        String IP = "";
        try {
            String address = "http://ip-api.com/json/?lang=zh-CN";
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setUseCaches(false);

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = connection.getInputStream();
                // 将流转化为字符串
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                String tmpString = "";
                StringBuilder retJSON = new StringBuilder();
                while ((tmpString = reader.readLine()) != null) {
                    retJSON.append(tmpString + "\n");
                }

                JSONObject jsonObject = new JSONObject(retJSON.toString());
                String status = jsonObject.getString("status");
                if (status.equals("success")) {
                    IP = "(" + jsonObject.getString("country")
                            + jsonObject.getString("regionName")
                            + jsonObject.getString("city") + ",ip:"
                            + jsonObject.getString("query") + ")";
                    CWLog.i("byou", "IPInfo==" + IP);
                    app_IP = IP;
                    String ipStr = jsonObject.getString("query");
                    BaseApplication.getInstance().setAPP_IP(ipStr);
                    CWLog.i("byou", "IP==" + ipStr);
                } else {
                    IP = "";
                }
            } else {
                IP = "";
            }
        } catch (Exception e) {
            IP = "";
        }
        return IP;
    }


    //获取模块
    private String getModuleNameByFeedBackId(int id) {
        String moduleName = id + "";
        switch (id) {
            case FEEDBACK_TYPE_LISTEN_SPEAK_WORK:
                moduleName = "听说模考";
                break;
            case FEEDBACK_TYPE_SENTENCE_SPEECH:
                moduleName = "句子跟读";
                break;
            case FEEDBACK_TYPE_WORD_SPEECH:
                moduleName = "单词跟读";
                break;
            case FEEDBACK_TYPE_HOMEWORK_LIST:
                moduleName = "作业列表";
                break;
            case FEEDBACK_TYPE_HASDONE__HOMEWORK_LIST:
                moduleName = "已完成作业列表";
                break;
            case FEEDBACK_TYPE_ONLINE_ANSWER:
                moduleName = "线上作答";
                break;

            case FEEDBACK_TYPE_INTERACTIVE_TUTORIAL:
                moduleName = "互动教程";
                break;
            case FEEDBACK_TYPE_EVALUATE:
                moduleName = "云知声评分";
                break;
            case FEEDBACK_TYPE_DOWNLOAD_RES:
                moduleName = "下载资源";
                break;
            case FEEDBACK_TYPE_ALIYUN_SUBMIT_WORK_RESULT:
                moduleName = "阿里云提交";
                break;
            case FEEDBACK_TYPE_WORD_LIST:
                moduleName = "练习册";
                break;
            case FEEDBACK_TYPE_BOOK_DESK:
                moduleName = "书桌";
                break;
            case FEEDBACK_TYPE_SUBMIT_WORK:
                moduleName = "提交作业反馈";
                break;
            case FEEDBACK_TYPE_REQUEST_ERROR:
                moduleName = "请求接口错误";
                break;
            case FEEDBACK_CRASH_TRACE_INFO:
                moduleName = "crash日志";
                break;
            case FEEDBACK_TYPE_SCAN_MODE:
                moduleName = "扫码";
                break;
            case FEEDBACK_TYPE_SYMBOL:
                moduleName = "音标打分";
                break;
            case FEEDBACK_TYPE_EARLIER_HOMEWORK_LIST:
                moduleName = "更早作业";
                break;
            case FEEDBACK_TYPE_DICTATION:
                moduleName = "报听写";
                break;
            case FEEDBACK_TYPE_MESSAGE:
                moduleName = "消息";
                break;
            case FEEDBACK_TYPE_SERVICE_UPLOAD_AUDIO:
                moduleName = "自定义服务上传音频";
                break;
        }
        return moduleName;
    }


    private String getEnvironmentName() {
        String name = "";
        int runEnv = BaseApplication.RUN_ENV;
        switch (runEnv) {
            case 2:
                name = "测试环境";
                break;
            case 3:
                name = "预发布环境";
                break;
            case 4:
                name = "正式环境";
                break;
            default:
                break;
        }
        return name;
    }

    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
